<template>
  <div class="app-container">
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <span style='font-size: 17px;'>基本信息</span>
      <el-form ref="form" :model="form" :rules="rules" label-width="115px" style='margin-top: 20px;'>
        <el-row>
          <el-col :span="12">
            <el-form-item label="组织名称" prop="name" :verify="verifyName">
              <el-input v-model="form.name" placeholder="请输入组织名称" :disabled="title == '查看组织'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="class">
              <!-- <el-input v-model="form.class" placeholder="部门"  /> -->
              <el-select v-model="form.class" placeholder="请选择" @change="changeClass"
                :disabled="title == '编辑组织' || title == '查看组织' || selectDis">
                <el-option v-for="item in classify" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title == '编辑组织' || title == '查看组织'">
            <el-form-item label="组织编码" prop="code">
              <el-input v-model="form.code" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" verify>
              <el-select v-model="form.status" :disabled="title == '查看组织'|| form.class == '企业'" placeholder="请选择">
                <el-option label="存续" :value="0" />
                <el-option label="注销" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织类型" prop="orgName">
              <el-input v-model="form.orgName" placeholder="内部" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级组织" prop="parentId">
              <!-- <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" /> -->
              <el-input v-model="form.parentId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12"
            v-if="resetOrg || form.class == '企业'">
            <el-form-item label="证件类型" prop="orgName">
              <el-input v-model="form.orgName" placeholder="统一社会信用代码" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12"
            v-if="resetOrg || form.class == '企业'">
            <el-form-item label="证件号码" prop="cardId"  :verify="verifyCode">
              <el-input v-model="form.cardId" :disabled="title == '查看组织'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="1" :max="sortMax"
                :disabled="title == '查看组织'" />
              <el-button v-if="(title == '编辑组织') || (title == '新建组织')" style="margin-left: 20px;font-size: 14px;"
                type="text" @click="setSort">拖动排序</el-button>
            </el-form-item>

          </el-col>
          <el-col :span="12" v-if="(title == '编辑组织' && typeOrg == true) || (title == '查看组织' && typeOrg == true)">
            <el-form-item label="法定代表人姓名" prop="legalPersonName">
              <el-input v-model="form.legalPersonName" :disabled="title == '查看组织'" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <template v-if="form.class == '企业'&& title != '新建组织'">
          <div style='font-size: 17px;padding: 10px 0;'>三方系统账号</div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="实名状态" >
                <el-select v-model="form.thirdAccountRealNameStatus" disabled placeholder="请选择">
                  <el-option label="未实名" :value="0" />
                  <el-option label="已实名" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="5G随意签SaaS账号">
                <el-input v-model="form.thirdAccount5G"  disabled/>
              </el-form-item>
            </el-col>
          </el-row>
        </template> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="submitForm">确 定</el-button>
        <el-button v-preventReClick @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!---移动至页面-->
    <el-dialog title="移动" :visible.sync="dialogVisible" width="400px">
      <el-form ref="form" :model="form" :rules="rules" label-width="115px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="待移动组织" prop="sourceName">
              <el-input v-model="run.sourceName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="移动到组织" prop="targetName" verify>
              <div class="border">
                <el-tag v-for="item in run.target" :key="item.id" closable @close="handleRemove(item)">{{ item.name
                }}</el-tag>
                <div class="add">
                  <el-button v-preventReClick plain size="mini" icon="el-icon-plus" @click="handleinit()">选择组织</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <userDialog ref="userDialog" :title="userTitle" @emitplayer="emitplayer"></userDialog>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="dialogVisible = false">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 拖动排序页面 -->
    <el-drawer title="排序" append-to-body custom-class="my-drawer" :wrapperClosable="false" :visible.sync="showSort"
      size="60%" :with-header="false">
      <div>
        <img style="width: 34px;margin-left: -35px;  margin-top: 2px;" src="../../../assets/images/close.png" alt
          @click="closeSort">
        <p style="display: inline; color:black;font-size: 18px; margin-left: 15px">排序</p>
      </div>
      <div>
        <el-table :data="tableData" border style="width: 90%;margin: 40px;">
          <el-table-column prop="sort" label="排位" align="center" width="180">
          </el-table-column>
          <el-table-column prop="name" label="组织名称" align="center">
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listDept, listSameLevel, getDept, addDept, updateDept, moveDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import userDialog from "@/components/common/userDialog/index.vue"
import { CommonStatusEnum } from '@/utils/constants'
import { getDictDatas, DICT_TYPE } from '@/utils/dict'
import { listSimpleUsers } from "@/api/system/user";
import { dataTool } from 'echarts';
import Sortable from 'sortablejs'

export default {
  name: "SystemDept",
  components: { Treeselect, userDialog },
  data() {
    return {
      selectDis: false,
      oldList: [],
      tableData: [],
      showSort: false,
      resetOrg: false,//是否为编辑企业||或者新建下级组织选了企业
      typeOrg: false,//false查看组织，true查看企业
      userTitle: '待移动组织',
      dialogVisible: false,
      autonym: true,//是否实名
      sortMax: undefined,
      getDeptObj: {},
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 用户下拉列表
      users: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        class: '',
        orgName: '内部'
      },
      classify: [{
        value: '部门',
        label: '部门',
      },
      {
        value: '企业',
        label: '企业'
      },],
      run: {
        target: [],
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        class: [
          { required: true, message: "分类选择不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      },

      // 枚举
      CommonStatusEnum: CommonStatusEnum,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS)
    };
  },
  created() {
    this.getList();
    // 获得用户列表
    listSimpleUsers().then(response => {
      this.users = response.data;
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.rowDrop();
    });
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },
    closeSort() {
      this.showSort = false
      let list = this.tableData.filter(v => v.code == this.form.code)
      this.$set(this.form, 'sort', list[0].sort)
    },
    rowDrop() {
      // tbody  拿到你要去操作的拖拽元素的父节点
      const that = this;
      const tbody1 = document.querySelectorAll(
        '.el-table__body-wrapper tbody'
      );
      new Sortable(tbody1[2], {//这里面会返回三个数据，最后一个才是想要的
        animation: 15,  //定义排序动画的时间  单位是ms 
        ghostClass: 'blue-background-class',   //drop placeholder的css类名  可以不设置
        //开始拖拽
        onStart: function (e) {
          e.oldIndex;  // 父元素索引
        },
        //结束拖拽
        onEnd: function (evt) {
          // 获取排序之后的data数据
          that.tableData.splice(evt.newIndex, 0, that.tableData.splice(evt.oldIndex, 1)[0])
          var newArray = that.tableData.slice(0)
          that.tableData = []
          that.$nextTick(function () {
            that.tableData = newArray
            that.tableData.forEach((item, index) => {
              that.$set(item, 'sort', index + 1);
            });
          })
        }
      });
    },
    setSort() {
      this.showSort = true
      if (this.form.hasChildren == 1) {
        listSameLevel({ id: this.form.childrenId }).then(response => {
          console.log(response.data, 'date---')
          this.tableData = response.data
          response.data.forEach((item, index) => {
            this.$set(this.tableData[index], 'sort', index + 1)
          });
          let dai = {
            code: this.form.code,
            id: undefined,
            name: this.form.name || '待新建组织',
            parentId: this.form.id || undefined,
            sort: this.tableData.length + 1,
          }
          this.tableData.push(dai)
        })
      } else {
        let dai = {
          code: undefined,
          id: undefined,
          name: this.form.name || '待新建组织',
          parentId: this.form.id || undefined,
          sort: this.tableData.length + 1,
        }
        this.tableData.push(dai)
      }
      this.$nextTick(() => {
        this.rowDrop();
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    changeClass(item) {
      if (item == '企业') {
        this.resetOrg = true
      } else {
        this.resetOrg = false
      }
      console.log(item, 'item-----')
    },
    submit() {
      let data = {
        sourceId: this.run.sourceId,
        targetId: this.run.target[0].id
      }
      moveDept(data).then(response => {
        this.$modal.msgSuccess("移动成功");
        this.$parent.refreshTree()
        this.dialogVisible = false
      })
    },
    //组织回调
    emitplayer(item = []) {
      this.$set(this.run, 'target', item)
      console.log(item, 'item----', this.run);
    },

    // 表单重置
    reset() {
      this.resetOrg = false
      this.form = {
        id: undefined,
        parentId: undefined,
        name: undefined,
        sort: undefined,
        leaderUserId: undefined,
        phone: undefined,
        email: undefined,
        status: '0',
      };
      this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleRemove(val) {
      this.run.target.splice(val, 1);
      console.log(this.run.target, 'this.val-', val, this.run)

    },
    handleinit() {
      this.$refs.userDialog.init('', this.run.target || [], this.run.sourceId)
    },
    /** 新增按钮操作 */
    handleAdd(row, command, sortMax, sort) {

      console.log(row, 'row---0000', sort, 'sort---', this.selectDis, this.form.class)
      if (row.treeSort == 1 || row.treeSort == 0) {//企业
        this.typeOrg = true
        if (command == 'c') {
          this.resetOrg = true//编辑企业
          console.log(this.resetOrg, 'this.resetOrg---')
        }
      } else {
        this.typeOrg = false
      }
      this.reset();
      this.open = true;
      if (!row.parentName) {
        this.selectDis = true
        this.form.class = '企业'
      } else {
        this.selectDis = false
      }
      if (row !== undefined) {
        this.form.parentId = row.parentId;
        this.sortMax = sortMax
        this.form.sort = sort
        this.form.id = row.id
        this.form.code = row.code
        if (row.children) {
          this.form.hasChildren = 1
          this.form.childrenId = row.children[0].id
        } else {
          this.form.hasChildren = 0
        }
      }
      if (command == 'a') {
        this.title = "新建组织";
        this.form.parentId = row.name;
        if (row.children) {
          this.sortMax = row.children.length + 1
          this.form.sort = this.sortMax
        } else {
          this.sortMax = 1
          this.form.sort = 1
        }

      } else if (command == 'b') {
        this.title = "查看组织";
        this.handleUpdate(row)
      } else if (command == 'c') {
        this.title = "编辑组织";
        this.form.parentName = row.parentName
        this.handleUpdate(row)
      } else {
        this.run.sourceName = row.name
        this.run.sourceId = row.id
        this.open = false
        this.dialogVisible = true
      }

      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //this.reset();
      getDept(row.id).then(response => {
        this.getDeptObj = response.data
        this.form = response.data;
        // if (this.form.parentId == undefined) { // 无父部门时，标记为 undefined，避免展示为 Unknown
        //   this.form.parentId = '无上级组织';
        // }
        this.form.parentId = response.data.parentId
        if (this.title == '编辑组织') {
          this.$set(this.form, 'name', row.name)
          this.$set(this.form, 'cardId', response.data.cardId)
          console.log('编辑组织', this.form, response.data)
        } else {
          this.form.name = row.name
          this.form.cardId = response.data.cardId
        }
        this.form.class = response.data.type == 1 ? '企业' : '部门'
        this.$set(this.form, 'legalPersonName', response.data.legalPersonName)
        //this.form.legalPersonName=response.data.legalPersonName
      });
      listDept(row.id).then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.title == "新建组织") {
        let data = {
          name: this.form.name,
          sort: this.form.sort,
          status: 0,
          hasChildren: this.form.hasChildren,
          parentId: this.form.id,
          type: this.form.class == '部门' ? 2 : 1
        }
        console.log(data, 'data', this.form)
        this.$refs.form.validate(valid => {
          if (valid) {
            addDept(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false
              this.$parent.refreshTree()
            })
          }
        })

      } else if (this.title == "编辑组织") {
        // let data = {
        //   name: this.form.name,
        //   sort: this.form.sort,
        //   status: this.form.status,
        //   id: this.form.id,
        //   cardId: this.form.cardId,
        //   parentId: this.form.parentName,
        //   legalPersonName: this.form.legalPersonName
        // }
        let params = Object.assign({}, this.getDeptObj, this.form)
        console.log(this.form, 'form---')
        this.$refs.form.validate(valid => {
          if (valid) {
            updateDept(params).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false
              this.$parent.refreshTree()
            })
          }
        })

      } else {
        this.open = false
      }
    },
    verifyName(rule, val, callback) {
      if (val) {
        if (val.length < 2 || val.length > 100) callback(Error('组织名称支持输入2-100个字'));
        let re = /^[\u4E00-\u9FA5A-Za-z]+$/;
        if (!re.test(val)) callback(Error('支持中文、英文（区分大小写）'));
        else callback();
      } else {
        callback();
      }
    },
    verifyCode(rule, val, callback) {
      if (val) {
        console.log('0909', val)
        if (val.length != 18) callback(Error('输入18位字符'));
        let re = /^[A-Z\d]+$/;
        if (!re.test(val)) callback(Error('格式错误，仅支持英文大写，阿拉伯数字'));
        else callback();
      } else {
        callback();
      }
    },
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
  width: 115px !important;
}

// ::v-deep  .el-form-item__content{
//   margin-left: 115px!important;
// }
::v-deep .el-select {
  width: 100%;
}

.border {
  width: 100%;
  height: 30px;
  border-radius: 5px;
  border: 1px solid #e7e8eb;
}

.add {
  display: inline-block;
}

::v-deep .my-drawer {
  overflow: visible !important;
}

::v-deep .my-drawer section {
  overflow: visible !important;
}
</style>
